package com.xingkeduo.business.order.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingkeduo.business.order.controller.CutomerServiceController;
import com.xingkeduo.business.order.domain.CutomerQueyService;
import com.xingkeduo.business.order.domain.OrderDomainService;
import com.xingkeduo.business.order.remote.AdminRemoteService;
import com.xingkeduo.business.order.remote.CommentRemoteService;
import com.xingkeduo.business.order.remote.StoreRemoteService;
import com.xingkeduo.business.order.remote.UserRemoteService;
import com.xingkeduo.business.order.remote.feign.AdminFeignService;
import com.xingkeduo.business.order.remote.feign.StoreFeignService;
import com.xingkeduo.dto.*;
import com.xingkeduo.dto.enums.*;
import com.xingkeduo.dto.param.*;
import com.xingkeduo.dto.response.*;
import com.xingkeduo.pojo.enums.OrderSource;
import com.xingkeduo.pojo.enums.OrderStatus;
import com.xingkeduo.pojo.enums.RefundType;
import com.xingkeduo.pojo.query.OrderOldMapper;
import com.xingkeduo.pojo.query.OrderDetailMapper;
import com.xingkeduo.pojo.query.OrderMapper;
import com.xingkeduo.pojo.query.OrderStatusLogMapper;
import com.xingkeduo.pojo.table.*;
import com.xingkeduo.util.pojo.exception.BusinessException;
import com.xingkeduo.utils.DateTimeUtils;
import com.xingkeduo.utils.PageResponseDTO;
import com.xingkeduo.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.xingkeduo.pojo.enums.OrderStatus.EVALUATION_DONE;
import static com.xingkeduo.pojo.enums.OrderStatus.IN_SERVICE;
import static com.xingkeduo.utils.DateTimeUtils.HH_mm;
import static com.xingkeduo.utils.DateTimeUtils.yyyy_MM_dd_H_m_s;

/**
 * @author chi  2019-02-14 16:56
 **/
@Service
@Slf4j
public class OrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private OrderStatusLogMapper orderStatusLogMapper;
    @Resource
    private UserRemoteService userRemoteService;
    @Resource
    private CommentRemoteService commentRemoteService;

    @Resource
    private StoreRemoteService storeRemoteService;

    @Resource
    private AdminRemoteService adminRemoteService;

    @Resource
    private OrderDomainService orderDomainService;
    @Resource
    private OrderRefundService orderRefundService;

    @Resource
    private AdminFeignService adminFeignService;

    @Resource
    private StoreFeignService storeFeignService;
    @Resource
    private OrderOldMapper orderOldMapper;

    @Resource
    private CutomerQueyService cutomerQueyService;


    /**
     * 分页查询
     *
     * @param orderQueryDto
     * @return
     */
    public PageResponseDTO selectListPage(OrderQueryDto orderQueryDto) {
        IPage<Order> page = new Page<>(orderQueryDto.getPageNo(), orderQueryDto.getPageSize());
        //构造查询参数
        LambdaQueryWrapper<Order> queryWrapper = generateQuery(orderQueryDto);

        IPage<Order> orderIPage = orderMapper.selectPage(page, queryWrapper);
        List<Order> records = orderIPage.getRecords();
        orderDomainService.queryOrdersDetail(records);
        List<OrderResponseDto> collect = records.stream().peek(this::complementInfo).map(this::covertToDto)
                .collect(Collectors.toList());
        PageResponseDTO<OrderResponseDto> dtos = new PageResponseDTO<>(orderIPage, collect);
        return dtos;
    }

    /**
     * 查询构造器
     *
     * @param query
     * @return
     */
    public LambdaQueryWrapper<Order> generateQuery(OrderQueryDto query) {
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();


        if (StringUtils.isNotBlank(query.getUserInfo()) || StringUtils.isNotBlank(query.getUserId())) {

            JSONObject jsonObject = new JSONObject();
            if (StringUtils.isNotBlank(query.getUserInfo())) {
                jsonObject.put("nameOrPhone", query.getUserInfo());
            }

            if (StringUtils.isNotBlank(query.getUserId())) {
                jsonObject.put("id", query.getUserId());
            }

            log.info("consumer param:{}", jsonObject.toJSONString());
            ResponseUtils<String[]> consumer = null;
            try {
                consumer = adminFeignService.consumer(URLEncoder.encode(jsonObject.toJSONString(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            log.info("consumer response:{}", JSON.toJSONString(consumer));

            if (consumer.success()) {
                String[] data = consumer.getData();

                if (data != null && data.length > 0) {
                    queryWrapper.in(Order::getUserId, data);
                } else {
                    queryWrapper.eq(Order::getId, 0L);
                }
            } else {
                queryWrapper.eq(Order::getId, 0L);
            }
        }


        if (StringUtils.isNotBlank(query.getWaitingLineNo())) {
            queryWrapper.like(Order::getWaitingLineNo, query.getWaitingLineNo());
        }

        if (StringUtils.isNotBlank(query.getVendorId())) {
            queryWrapper.eq(Order::getVendorId, query.getVendorId());
        }

        if (StringUtils.isNotBlank(query.getCityId())) {
            queryWrapper.eq(Order::getCityId, query.getCityId());
        }

        if (StringUtils.isNotBlank(query.getBranchOfficeId())) {
            queryWrapper.eq(Order::getBranchOfficeId, query.getBranchOfficeId());
        }

        if (StringUtils.isNotBlank(query.getStoreId())) {
            queryWrapper.eq(Order::getStoreId, query.getStoreId());
        }

        if (StringUtils.isNotBlank(query.getServiceTypeId())) {
            queryWrapper.eq(Order::getServiceTypeId, query.getServiceTypeId());
        }

        if (StringUtils.isNotBlank(query.getOrderNo())) {
            queryWrapper.like(Order::getOrderNo, query.getOrderNo());
        }

        if (StringUtils.isNotBlank(query.getAdminName())) {

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("condition", query.getAdminName());


            log.info("admin param:{}", jsonObject.toJSONString());
            ResponseUtils<String[]> responseUtils = null;
            try {
                responseUtils = adminFeignService.adminCondition(URLEncoder.encode(jsonObject.toJSONString(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            log.info("admin response:{}", JSON.toJSONString(responseUtils));
            if (responseUtils.success()) {
                String[] data = responseUtils.getData();

                if (data != null && data.length > 0) {
                    queryWrapper.in(Order::getAppointmentAdminId, data);
                } else {
                    queryWrapper.eq(Order::getId, 0L);
                }

            } else {
                queryWrapper.eq(Order::getId, 0L);
            }
        }

        if (query.getPayType() != null) {
            queryWrapper.eq(Order::getPayType, query.getPayType());
        }

        if (query.getOrderSource() != null) {
            queryWrapper.eq(Order::getOrderSource, query.getOrderSource());
        }

        if (query.getStatus() != null) {
            queryWrapper.eq(Order::getStatus, query.getStatus());
        }

        if (StringUtils.isNotBlank(query.getTimeStart()) || StringUtils.isNotBlank(query.getTimeEnd())) {

            String timeStart = query.getTimeStart();
            String timeEnd = query.getTimeEnd();

            if (StringUtils.isBlank(timeStart)) {
                timeStart = "1991-03-29";
            }
            if (StringUtils.isBlank(timeEnd)) {
                timeEnd = "2100-01-01";
            }

            timeStart = timeStart + " 0:0:0";
            timeEnd = timeEnd + " 23:59:59";

            queryWrapper.between(Order::getCreatedTime, DateTimeUtils.yyyy_MM_dd_H_m_s(timeStart), DateTimeUtils.yyyy_MM_dd_H_m_s(timeEnd));
        }


        queryWrapper.orderByDesc(Order::getCreatedTime);
        return queryWrapper;
    }


    /**
     * 用户查询器
     *
     * @param query
     * @return
     */
    public LambdaQueryWrapper<Order> generateUserQuery(OrderUserQueryDto query) {
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        String userId = query.getUserId();
        OrderQueryStatus orderQueryStatus = query.getOrderQueryStatus();
        // 获取账号合并ids
        String[] strings = adminRemoteService.queryUserIds(userId);
        queryWrapper.in(Order::getUserId, strings);
//        queryWrapper.eq(Order::getUserId, userId);
        switch (orderQueryStatus) {
            case PAID: {
                queryWrapper.in(Order::getStatus, new OrderStatus[]{OrderStatus.PAID, OrderStatus.OVER_NUMBER, IN_SERVICE});
                break;
            }
            case REFUND_DONE: {
                queryWrapper.eq(Order::getStatus, OrderStatus.REFUND_DONE);
                break;
            }
            case TO_BE_COMMENT: {
                // 2,3,-1,6,7,9 服务完成并且 没有评价
                queryWrapper.in(Order::getStatus, new OrderStatus[]{EVALUATION_DONE, OrderStatus.HAIRCUT_DONE, OrderStatus.REFUND_APPLY, OrderStatus.REFUND_ERROR, OrderStatus.REFUND_ACCEPT, OrderStatus.REFUND_REGECT});
                queryWrapper.eq(Order::getServiceDown, true);
                queryWrapper.eq(Order::getHadComment, false);
                break;
            }
            case SERVICE_DOWN: {
                // 3,-1,6,7,9 服务完成并且有评价
                queryWrapper.eq(Order::getHadComment, true);
                queryWrapper.eq(Order::getServiceDown, true);
                queryWrapper.in(Order::getStatus, new OrderStatus[]{EVALUATION_DONE, OrderStatus.REFUND_APPLY, OrderStatus.REFUND_ERROR, OrderStatus.REFUND_ACCEPT, OrderStatus.REFUND_REGECT});
                break;
            }
            case ALL: {
                //状态：-2  -1，1，2，3，5，6，7，8，9
                queryWrapper.in(Order::getStatus, new OrderStatus[]{OrderStatus.REFUND_DONE, OrderStatus.REFUND_APPLY, OrderStatus.PAID, OrderStatus.HAIRCUT_DONE, EVALUATION_DONE, OrderStatus.OVER_NUMBER, OrderStatus.REFUND_ERROR, OrderStatus.REFUND_ACCEPT, IN_SERVICE, OrderStatus.REFUND_REGECT});
                break;
            }
        }

        queryWrapper.notIn(Order::getOrderSource, OrderSource.SUI_XING_FU);
        queryWrapper.orderByDesc(Order::getCreatedTime);
        return queryWrapper;
    }


    public LambdaQueryWrapper<Order> generateAdminQuery(OrderAdminQueryDto queryDto) {
        String adminId = queryDto.getAdminId();

        String storeId = queryDto.getStoreId();

        OrderQueryStatus orderQueryStatus = queryDto.getOrderQueryStatus();

        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();

        if (StringUtils.isNotBlank(storeId)) {
            queryWrapper.eq(Order::getStoreId, storeId);
        }

        if (orderQueryStatus != null) {
            switch (orderQueryStatus) {
                case PAID: {
                    queryWrapper.eq(Order::getAppointmentAdminId, adminId);
                    queryWrapper.eq(Order::getStatus, OrderStatus.PAID);
                    queryWrapper.between(Order::getAppointmentStartTime, DateTimeUtils.startOfDay(LocalDateTime.now()), DateTimeUtils.endOfDay(LocalDateTime.now()));
                    break;
                }
                case SERVICE_DOWN: {
                    queryWrapper.eq(Order::getAdminId, adminId);
                    queryWrapper.eq(Order::getServiceDown, true);
                    queryWrapper.notIn(Order::getStatus, OrderStatus.REFUND_DONE);
                    queryWrapper.between(Order::getServeStartTime, DateTimeUtils.startOfDay(LocalDateTime.now()), DateTimeUtils.endOfDay(LocalDateTime.now()));
                    break;
                }
                case REFUND_OVERNUMBER: {
                    // 7.已退款/已过号订单列表，需要展示2种订单，按照预约时间排序
                    //• 预约时间在今日，预约发型师是本人，已过号的订单
                    //• 预约时间在今日，还没开始服务，用户已经退款的订单
                    //• 服务时间在今日，服务发型师是本人，已退款成功的订单

                    queryWrapper.nested(i -> i
                            //• 预约时间在今日，预约发型师是本人，已过号的订单
                            .eq(Order::getAppointmentAdminId, adminId)
                            .eq(Order::getStatus, OrderStatus.OVER_NUMBER)
                            .between(Order::getAppointmentStartTime, DateTimeUtils.startOfDay(LocalDateTime.now()), DateTimeUtils.endOfDay(LocalDateTime.now()))
                            .or()
                            //• 预约时间在今日，还没开始服务，用户已经退款的订单
                            .eq(Order::getAppointmentAdminId, adminId)
                            .eq(Order::getStatus, OrderStatus.REFUND_DONE)
                            .between(Order::getAppointmentStartTime, DateTimeUtils.startOfDay(LocalDateTime.now()), DateTimeUtils.endOfDay(LocalDateTime.now()))
                            .eq(Order::getServiceDown, false)
                            .or()
                            //• 服务时间在今日，服务发型师是本人，已退款成功的订单
                            .eq(Order::getAdminId, adminId)
                            .eq(Order::getStatus, OrderStatus.REFUND_DONE)
                            .between(Order::getServeStartTime, DateTimeUtils.startOfDay(LocalDateTime.now()), DateTimeUtils.endOfDay(LocalDateTime.now()))
                            .eq(Order::getServiceDown, true)
                    );

                    break;
                }
                case PAID_INSERVICE: {
                    queryWrapper.nested(i -> i
                            .eq(Order::getAppointmentAdminId, adminId)
                            .eq(Order::getStatus, OrderStatus.PAID)
                            .between(Order::getAppointmentStartTime, DateTimeUtils.startOfDay(LocalDateTime.now()), DateTimeUtils.endOfDay(LocalDateTime.now()))
                            .or()
                            .eq(Order::getAdminId, adminId)
                            .eq(Order::getStatus, IN_SERVICE)
                            .between(Order::getAppointmentStartTime, DateTimeUtils.startOfDay(LocalDateTime.now()), DateTimeUtils.endOfDay(LocalDateTime.now()))
                    );
                }
            }
        }

        queryWrapper.orderByAsc(Order::getAppointmentStartTime);
        return queryWrapper;
    }

    public LambdaQueryWrapper<OrderRefund> generateAdminHistoryQueryRefund(OrderAdminHistoryQueryDto query) {
        LambdaQueryWrapper<OrderRefund> queryWrapper = new QueryWrapper<OrderRefund>().lambda();

        queryWrapper.eq(OrderRefund::getRefundType, RefundType.ADMIN);

        OrderQueryAdminRefundEnum refundStatus = query.getRefundStatus();
        if (refundStatus != null) {
            switch (refundStatus) {
                case REFUND_APPLY: {
                    queryWrapper.eq(OrderRefund::getRefundStatus, OrderStatus.REFUND_APPLY.getValue());
                    break;
                }
                case REFUND_ACCEPT: {
                    queryWrapper.in(OrderRefund::getRefundStatus, new String[]{OrderStatus.REFUND_ACCEPT.getValue(), OrderStatus.REFUND_DONE.getValue(), OrderStatus.REFUND_ERROR.getValue()});
                    break;
                }
                case REFUND_REGECT: {
                    queryWrapper.eq(OrderRefund::getRefundStatus, OrderStatus.REFUND_REGECT.getValue());
                    break;
                }
            }
        }


        if (StringUtils.isBlank(query.getStoreId()) && StringUtils.isBlank(query.getAdminId())) {
            queryWrapper.eq(OrderRefund::getId, 0L);
        } else {
            if (StringUtils.isNotBlank(query.getStoreId())) {
                queryWrapper.eq(OrderRefund::getStoreId, query.getStoreId());
            }

            if (StringUtils.isNotBlank(query.getAdminId())) {
                queryWrapper.eq(OrderRefund::getAdminId, query.getAdminId());
            }
        }


        if (StringUtils.isNotBlank(query.getOrderNo())) {
            queryWrapper.eq(OrderRefund::getOrderNo, query.getOrderNo());
        }


        if (StringUtils.isNotBlank(query.getServeStartTime()) || StringUtils.isNotBlank(query.getServeEndTime())) {

            String payTimeStart = query.getServeStartTime();
            String payTimeEnd = query.getServeEndTime();

            if (StringUtils.isBlank(payTimeStart)) {
                payTimeStart = "1991-03-29 00:00";
            }
            if (StringUtils.isBlank(payTimeEnd)) {
                payTimeEnd = "2100-01-01 00:00";
            }
            queryWrapper.between(OrderRefund::getServeStartTime, DateTimeUtils.yyyy_M_d_H_m(payTimeStart), DateTimeUtils.yyyy_M_d_H_m(payTimeEnd));
        }


        queryWrapper.orderByDesc(OrderRefund::getSponsorTime);

        return queryWrapper;
    }


    public LambdaQueryWrapper<Order> generateAdminHistoryQuery(OrderAdminHistoryQueryDto query, OrderQueryTypeEnum orderQueryTypeEnum) {
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();


        if (StringUtils.isNotBlank(query.getOrderNo())) {
            queryWrapper.eq(Order::getOrderNo, query.getOrderNo());
        }

        if (StringUtils.isNotBlank(query.getUserMobile())) {
            queryWrapper.eq(Order::getUserMobile, query.getUserMobile());
        }

        if (StringUtils.isNotBlank(query.getServeStartTime()) || StringUtils.isNotBlank(query.getServeEndTime())) {

            String payTimeStart = query.getServeStartTime();
            String payTimeEnd = query.getServeEndTime();

            if (StringUtils.isBlank(payTimeStart)) {
                payTimeStart = "1991-03-29 00:00";
            }
            if (StringUtils.isBlank(payTimeEnd)) {
                payTimeEnd = "2100-01-01 00:00";
            }

            if(OrderQueryTypeEnum.SERVICE.equals(orderQueryTypeEnum)){
                queryWrapper.between(Order::getServeStartTime, DateTimeUtils.yyyy_M_d_H_m(payTimeStart), DateTimeUtils.yyyy_M_d_H_m(payTimeEnd));
            }else {
                queryWrapper.between(Order::getAppointmentStartTime, DateTimeUtils.yyyy_M_d_H_m(payTimeStart), DateTimeUtils.yyyy_M_d_H_m(payTimeEnd));
            }

        }

        if (StringUtils.isNotBlank(query.getAppointmentStartTime()) || StringUtils.isNotBlank(query.getAppointmentEndTime())) {

            String timeStart = query.getAppointmentStartTime();
            String timeEnd = query.getAppointmentEndTime();

            if (StringUtils.isBlank(timeStart)) {
                timeStart = "1991-03-29 00:00";
            }
            if (StringUtils.isBlank(timeEnd)) {
                timeEnd = "2100-01-01 00:00";
            }
            queryWrapper.between(Order::getAppointmentStartTime, DateTimeUtils.yyyy_M_d_H_m(timeStart), DateTimeUtils.yyyy_M_d_H_m(timeEnd));
        }


        if (OrderQueryTypeEnum.APPOINTMENT.equals(orderQueryTypeEnum)) {
            queryWrapper.eq(Order::getServiceDown, false);
            OrderQueryAdminAppointmentEnum appointmentStatus = query.getAppointmentStatus();
            if (appointmentStatus != null) {
                switch (appointmentStatus) {
                    case OVER_NUMBER: {
                        queryWrapper.eq(Order::getStatus, OrderStatus.OVER_NUMBER);
                        break;
                    }
                    case PAID: {
                        queryWrapper.eq(Order::getStatus, OrderStatus.PAID);
                        break;
                    }
                    case APPOINTMENT_REFUND: {
                        queryWrapper.eq(Order::getStatus, OrderStatus.REFUND_DONE);
                        queryWrapper.eq(Order::getServiceDown, false);
                        break;
                    }
                }
            } else {
                queryWrapper.in(Order::getStatus, new OrderStatus[]{OrderStatus.OVER_NUMBER, OrderStatus.PAID, OrderStatus.REFUND_DONE});
                queryWrapper.eq(Order::getServiceDown, false);
            }

            if (StringUtils.isBlank(query.getAppointmentAdminId()) && StringUtils.isBlank(query.getStoreId())) {
                queryWrapper.eq(Order::getId, 0L);
            } else {
                if (StringUtils.isNotBlank(query.getStoreId())) {
                    queryWrapper.eq(Order::getStoreId, query.getStoreId());
                }
                if (StringUtils.isNotBlank(query.getAppointmentAdminId())) {
                    queryWrapper.eq(Order::getAppointmentAdminId, query.getAppointmentAdminId());
                }
            }


        } else if (OrderQueryTypeEnum.SERVICE.equals(orderQueryTypeEnum)) {

            if (StringUtils.isBlank(query.getAdminId()) && StringUtils.isBlank(query.getStoreId())) {
                queryWrapper.eq(Order::getId, 0L);
            } else {
                if (StringUtils.isNotBlank(query.getStoreId())) {
                    queryWrapper.eq(Order::getStoreId, query.getStoreId());
                }
                if (StringUtils.isNotBlank(query.getAdminId())) {
                    queryWrapper.eq(Order::getAdminId, query.getAdminId());
                }
            }

            OrderQueryAdminServiceEnum serviceStatus = query.getServiceStatus();
            if (serviceStatus != null) {
                switch (serviceStatus) {
                    case SERVICE_DOWN: {
                        queryWrapper.eq(Order::getServiceDown, true);
                        break;
                    }
                    case IN_SERVICE: {
                        queryWrapper.eq(Order::getStatus, IN_SERVICE);
                        break;
                    }
                    case SERVICE_REFUND: {
                        queryWrapper.eq(Order::getStatus, OrderStatus.REFUND_DONE);
                        queryWrapper.eq(Order::getServiceDown, true);
                        break;
                    }
                }
            } else {

                queryWrapper.nested(i -> i
                        .in(Order::getStatus, new OrderStatus[]{EVALUATION_DONE, OrderStatus.REFUND_APPLY, OrderStatus.REFUND_ACCEPT, OrderStatus.REFUND_REGECT, OrderStatus.REFUND_ERROR, OrderStatus.REFUND_DONE})
                        .eq(Order::getServiceDown, true)
                        .or()
                        .eq(Order::getStatus, IN_SERVICE)
                );


            }
        }

        if (OrderQueryTypeEnum.APPOINTMENT.equals(orderQueryTypeEnum)) {
            queryWrapper.orderByDesc(Order::getAppointmentStartTime);
        } else if (OrderQueryTypeEnum.SERVICE.equals(orderQueryTypeEnum)) {
            queryWrapper.orderByDesc(Order::getServeStartTime);
        } else if (OrderQueryTypeEnum.REFUND.equals(orderQueryTypeEnum)) {
            queryWrapper.orderByDesc(Order::getPayTime);
        }

        return queryWrapper;
    }


    public Order getOrderById(Serializable id) {
        if (id == null) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "订单不存在");
        }
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "订单不存在");
        }
        supplementOrder(order);
        return order;
    }

    public Order queryOrder(String orderNo) {
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().lambda().eq(Order::getOrderNo, orderNo).last("LIMIT 1"));
        if (order == null) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "订单不存在");
        }
        supplementOrder(order);
        return order;
    }


    /**
     * 取消订单
     *
     * @param userId
     * @param orderNo
     * @return
     */
    public Order getOrderByIdNo(String userId, String orderNo) {
        String[] strings = adminRemoteService.queryUserIds(userId);
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().lambda().in(Order::getUserId, strings).eq(Order::getOrderNo, orderNo).last("LIMIT 1"));
        if (order == null) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "订单不存在");
        }
        supplementOrder(order);
        return order;
    }

    public OrderDetailResponseDto queryById(Integer id, boolean detail) {
        Order order = getOrderById(id);
        OrderDetailResponseDto orderDetailResponseDto = new OrderDetailResponseDto();
        BeanUtils.copyProperties(order, orderDetailResponseDto);

        orderDetailResponseDto.setStatusName(order.getStatus().getValue());
        orderDetailResponseDto.setServiceTypeName(order.getServiceTypeName());
        orderDetailResponseDto.setPayTypeName(order.getPayType() != null ? order.getPayType().getValue() : "");
        orderDetailResponseDto.setOrderSourceName(order.getOrderSource().getName());


        try {
            String s = order.getAppointmentStartTime().toLocalDate() + " " + order.getAppointmentStartTime().toLocalTime().format(HH_mm) + "~" + order.getAppointmentEndTime().toLocalTime().format(HH_mm);
            orderDetailResponseDto.setAppointmentTimeShow(s);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String s1 = order.getServeStartTime().toLocalDate() + " " + order.getServeStartTime().toLocalTime().format(HH_mm) + "~" + order.getServeEndTime().toLocalTime().format(HH_mm);
            orderDetailResponseDto.setServiceTimeShow(s1);
        } catch (Exception e) {
        }

        try {
            orderDetailResponseDto.setServiceTimeLast(DateTimeUtils.minuteAndSecond(order.getServeStartTime(), order.getServeEndTime()));
        } catch (Exception e) {
        }

        if (!detail) {
            return orderDetailResponseDto;
        }

        Optional<OrderRefund> refundById = orderRefundService.getRefundById(order.getId());
        refundById.ifPresent(orderRefund -> {
            orderDetailResponseDto.setRefundType(orderRefund.getRefundType().getValue());
            orderDetailResponseDto.setRefundReason(orderRefund.getRefundReason());
        });


        OrderDetail orderDetail = orderDetailMapper.selectOne(new QueryWrapper<OrderDetail>().lambda().eq(OrderDetail::getOrderNo, order.getOrderNo()).last("LIMIT 1"));

        if (orderDetail != null) {
            BeanUtils.copyProperties(orderDetail, orderDetailResponseDto);
        }
        if (order.getHadComment()) {
            orderDetailResponseDto.setComments(commentRemoteService.getComment(order.getId()));
        }

        List<OrderStatusLog> orderStatusLogs = orderStatusLogMapper.selectList(new QueryWrapper<OrderStatusLog>().lambda().eq(OrderStatusLog::getOrderId, id).orderByAsc(OrderStatusLog::getCreatedTime));
        if (orderStatusLogs != null && orderStatusLogs.size() > 0) {
            orderStatusLogs = orderStatusLogs.stream().peek(orderStatusLog -> {
                orderStatusLog.setNewStatusName(orderStatusLog.getNewStatus().getValue());
                if (orderStatusLog.getCreatedBy() > 0) {
                    long createdBy = orderStatusLog.getCreatedBy();

                    String s = orderStatusLog.getOrderAction().toString();
                    if (s.contains("后台")) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", createdBy);
                        ResponseUtils<ManagerTable> managerTableResponseUtils = storeFeignService.manager_id(jsonObject.toJSONString());
                        if (managerTableResponseUtils != null && managerTableResponseUtils.success()) {
                            ManagerTable data = managerTableResponseUtils.getData();
                            orderStatusLog.setModifyName(data.getRealname());
                            orderStatusLog.setModifyNickName(data.getName());
                            orderStatusLog.setModifyCode(createdBy + "");
                        }
                    } else {
                        CraftsmanDTO admin = adminRemoteService.getAdmin(createdBy + "");
                        if (admin != null) {
                            orderStatusLog.setModifyName(admin.getName());
                            orderStatusLog.setModifyNickName(admin.getNickName());
                            orderStatusLog.setModifyCode(admin.getCode() + "");
                        }
                    }
                }
            }).collect(Collectors.toList());
        }
        orderDetailResponseDto.setOrderStatusLogs(orderStatusLogs);
        orderDetailResponseDto.covert();

        if(order.getServeStartTime()==null){
            orderDetailResponseDto.setAdminId(null);
            orderDetailResponseDto.setAdminName(null);
            orderDetailResponseDto.setAdminNickName(null);
            orderDetailResponseDto.setAdminCode(null);
            orderDetailResponseDto.setAdminAvatar(null);
        }


        return orderDetailResponseDto;
    }


    public OrderDetailResponseDto queryByOrderNO(String id, boolean detail) {
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().lambda().eq(Order::getOrderNo, id).last("LIMIT 1"));
        if (order == null) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "订单不存在");
        }
        supplementOrder(order);
        OrderDetailResponseDto orderDetailResponseDto = new OrderDetailResponseDto();
        BeanUtils.copyProperties(order, orderDetailResponseDto);

        orderDetailResponseDto.setStatusName(order.getStatus().getValue());
        orderDetailResponseDto.setServiceTypeName(order.getServiceTypeName());
        orderDetailResponseDto.setPayTypeName(order.getPayType() != null ? order.getPayType().getValue() : "");
        orderDetailResponseDto.setOrderSourceName(order.getOrderSource().getName());

        try {
            String s = order.getAppointmentStartTime().toLocalDate() + " " + order.getAppointmentStartTime().toLocalTime().format(HH_mm) + "~" + order.getAppointmentEndTime().toLocalTime().format(HH_mm);
            orderDetailResponseDto.setAppointmentTimeShow(s);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String s1 = order.getServeStartTime().toLocalDate() + " " + order.getServeStartTime().toLocalTime().format(HH_mm) + "~" + order.getServeEndTime().toLocalTime().format(HH_mm);
            orderDetailResponseDto.setServiceTimeShow(s1);
        } catch (Exception e) {
        }

        try {
            orderDetailResponseDto.setServiceTimeLast(DateTimeUtils.minuteAndSecond(order.getServeStartTime(), order.getServeEndTime()));
        } catch (Exception e) {
        }

        if (!detail) {
            return orderDetailResponseDto;
        }

        OrderDetail orderDetail = orderDetailMapper.selectOne(new QueryWrapper<OrderDetail>().lambda().eq(OrderDetail::getOrderNo, order.getOrderNo()).last("LIMIT 1"));

        if (orderDetail != null) {
            BeanUtils.copyProperties(orderDetail, orderDetailResponseDto);
        }
        orderDetailResponseDto.setComments(commentRemoteService.getComment(order.getId()));

        List<OrderStatusLog> orderStatusLogs = orderStatusLogMapper.selectList(new QueryWrapper<OrderStatusLog>().lambda().eq(OrderStatusLog::getOrderId, id).orderByDesc(OrderStatusLog::getCreatedTime));
        if (orderStatusLogs != null && orderStatusLogs.size() > 0) {
            orderStatusLogs = orderStatusLogs.stream().peek(orderStatusLog -> {
                orderStatusLog.setNewStatusName(orderStatusLog.getNewStatus().getValue());
                if (orderStatusLog.getCreatedBy() > 0) {
                    long createdBy = orderStatusLog.getCreatedBy();
                    CraftsmanDTO admin = adminRemoteService.getAdmin(createdBy + "");
                    orderStatusLog.setModifyName(admin.getName());
                    orderStatusLog.setModifyNickName(admin.getNickName());
                    orderStatusLog.setModifyCode(admin.getCode() + "");
                }
            }).collect(Collectors.toList());
        }
        orderDetailResponseDto.setOrderStatusLogs(orderStatusLogs);
        return orderDetailResponseDto;
    }

    /**
     * 根据orderNo 查询订单信息
     *
     * @param orderNo
     * @return
     */
    public OrderDetailResponseDto queryByOrderNO(String orderNo) {
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().lambda().eq(Order::getOrderNo, orderNo).last("LIMIT 1"));
        if (order == null) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "订单不存在");
        }
        supplementOrder(order);

        //门店详情
        StoreRemoteDto storeRemoteDto = storeRemoteService.queryStore(order.getStoreId(), order.getServiceTypeId());
        if (storeRemoteDto != null) {
            BeanUtils.copyProperties(storeRemoteDto, order);

        }

        OrderDetailResponseDto orderDetailResponseDto = new OrderDetailResponseDto();
        BeanUtils.copyProperties(order, orderDetailResponseDto);

        orderDetailResponseDto.setStatusName(order.getStatus().getValue());
        orderDetailResponseDto.setServiceTypeName(order.getServiceTypeName());
        orderDetailResponseDto.setPayTypeName(order.getPayType() != null ? order.getPayType().getValue() : "");
        orderDetailResponseDto.setOrderSourceName(order.getOrderSource().getName());

        try {
            String s = order.getAppointmentStartTime().toLocalDate() + " " + order.getAppointmentStartTime().toLocalTime().format(HH_mm) + "~" + order.getAppointmentEndTime().toLocalTime().format(HH_mm);
            orderDetailResponseDto.setAppointmentTimeShow(s);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String s1 = order.getServeStartTime().toLocalDate() + " " + order.getServeStartTime().toLocalTime().format(HH_mm) + "~" + order.getServeEndTime().toLocalTime().format(HH_mm);
            orderDetailResponseDto.setServiceTimeShow(s1);
        } catch (Exception e) {
        }

        try {
            orderDetailResponseDto.setServiceTimeLast(DateTimeUtils.minuteAndSecond(order.getServeStartTime(), order.getServeEndTime()));
        } catch (Exception e) {
        }
        String qrcodeUrl = orderDomainService.qrcodeUrl(orderDetailResponseDto.getTicketCode(), orderDetailResponseDto.getStoreId());
        orderDetailResponseDto.setTicketCodeUlr(qrcodeUrl);
        return orderDetailResponseDto;

    }

    public Order queryOrderByOrderNO(String orderNo) {
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().lambda().eq(Order::getOrderNo, orderNo).last("LIMIT 1"));
        if (order == null) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "订单不存在");
        }
        supplementOrder(order);
        return order;

    }

    /**
     * 查询标签
     *
     * @param userId
     * @param appointmentAdminId
     * @return
     */
    public String getLabels(String userId, String appointmentAdminId) {

//        首次约你   用户是否首次预约该发型师
//        你剪过2次   用户被本发型师服务的次数
//        共服务35次   用户在星客多服务的总次数
//        210 天前剪过   用户距离上一次服务的天数，如果没有服务订单，则不显示
        //指定客

        String[] strings = adminRemoteService.queryUserIds(userId);
        String a = "";
        Integer count = orderMapper.selectCount(new QueryWrapper<Order>().lambda()
                .in(Order::getUserId, strings)
                .eq(Order::getAdminId, appointmentAdminId)
                .eq(Order::getServiceDown, true)
        );
        count = count + orderOldMapper.selectCount(new QueryWrapper<OrderOld>().lambda()
                .in(OrderOld::getFUserId, strings)
                .eq(OrderOld::getFAdminId, appointmentAdminId)
                .gt(OrderOld::getFStatus, 1)
        );
        if (count == null || count == 0) {
            a += "首次约你,";
        } else {
            a += "指定客,";
            a += "你剪过" + count + "次,";
        }

        Integer count1 = orderMapper.selectCount(new QueryWrapper<Order>().lambda().in(Order::getUserId, strings).eq(Order::getServiceDown, true));
        count1 = count1 + orderOldMapper.selectCount(new QueryWrapper<OrderOld>().lambda()
                .in(OrderOld::getFUserId, strings)
                .gt(OrderOld::getFStatus, 1)
        );
        if (count1 > 0) {
            a += "共服务" + count1 + "次,";

            Order order = orderMapper.selectOne(new QueryWrapper<Order>().lambda().in(Order::getUserId, strings).eq(Order::getServiceDown, true).orderByDesc(Order::getServeStartTime).last("LIMIT 1"));
            if (order != null) {

                LocalDateTime serveEndTime = order.getServeEndTime();
                Duration duration = Duration.between(serveEndTime, LocalDateTime.now());
                long l = duration.toDays();
                if (l > 0) {
                    a += l + "天前剪过,";
                }
            } else {
                OrderOld orderOld = orderOldMapper.selectOne(new QueryWrapper<OrderOld>().lambda()
                        .in(OrderOld::getFUserId, strings)
                        .gt(OrderOld::getFStatus, 1)
                        .orderByDesc(OrderOld::getFServeStartTime)
                        .last("LIMIT 1")
                );

                if (orderOld != null) {
                    Integer fServeStartTime = orderOld.getFServeStartTime();
                    if(fServeStartTime==0){
                        fServeStartTime = orderOld.getFCreatetime();
                    }
                    LocalDateTime dateTime = LocalDateTime.ofEpochSecond(fServeStartTime, 0, ZoneOffset.ofHours(8));
                    Duration duration = Duration.between(dateTime, LocalDateTime.now());
                    long l = duration.toDays();
                    if (l > 0) {
                        a += l + "天前剪过,";
                    }
                }

            }
        }

        return a;
    }


    /**
     * 发型师端订单列表  实体转换
     *
     * @param order
     * @return
     */
    public OrderAdminResponseDto covertToOrderAdminResponseDto(Order order) {
        if (order == null) {
            return null;
        }
//        supplementOrder(order);
        OrderAdminResponseDto orderAdminResponseDto = new OrderAdminResponseDto();
        BeanUtils.copyProperties(order, orderAdminResponseDto);

        List<String> list = new ArrayList<>();

        String labels = order.getLabels();
        if (StringUtils.isNotBlank(labels)) {
            String[] split = labels.split(",");
            list.addAll(Arrays.asList(split));
        }
        orderAdminResponseDto.setLabels(list);

        if (StringUtils.isNotBlank(order.getUserId())) {
            Optional<UserRemoteDto> byUserId = userRemoteService.getByUserId(order.getUserId());
            byUserId.ifPresent(userRemoteDto -> {
                orderAdminResponseDto.setUserHeadUrl(userRemoteDto.getUserHeadUrl());
            });
        }

        if (IN_SERVICE.equals(order.getStatus())) {
            orderAdminResponseDto.setServeLastSeconds(Duration.between(order.getServeStartTime(), LocalDateTime.now()).getSeconds());
        }

        return orderAdminResponseDto;
    }


    /**
     * 用户端订单列表  实体转换
     *
     * @param order
     * @return
     */
    public OrderUserResponseDto covertToOrderUserResponseDto(Order order) {
        if (order == null) {
            return null;
        }
//        supplementOrder(order);
        OrderUserResponseDto orderUserResponseDto = new OrderUserResponseDto();
        BeanUtils.copyProperties(order, orderUserResponseDto);
        orderUserResponseDto.setStatusName(order.getStatus().getValue());

        if (order.getServiceDown() != null && order.getServiceDown()) {
            if (order.getHadComment() != null && !order.getHadComment()) {
                orderUserResponseDto.setStatusName("待评价");
            }
            orderUserResponseDto.setStatusName("已完成");
        }

        return orderUserResponseDto;
    }


    /**
     * cms端订单列表  实体转换
     *
     * @param order
     * @return
     */
    private OrderResponseDto covertToDto(Order order) {
        if (order == null) {
            return null;
        }
//        supplementOrder(order);
        OrderResponseDto orderResponseDto = new OrderResponseDto();
        BeanUtils.copyProperties(order, orderResponseDto);

        if (order.getPayType() != null) {
            orderResponseDto.setPayTypeName(order.getPayType().getValue());
            try {
                orderResponseDto.setPayTimeName(order.getPayTime().format(yyyy_MM_dd_H_m_s));
            } catch (Exception e) {
            }
        }

        orderResponseDto.setServiceTypeName(order.getServiceTypeName());
        orderResponseDto.setStatusName(order.getStatus().getValue());


        LocalDateTime appointmentStartTime = order.getAppointmentStartTime();
        LocalDateTime appointmentEndTime = order.getAppointmentEndTime();

        if (appointmentStartTime != null && appointmentEndTime != null) {
            orderResponseDto.setAppointmentTimeName(appointmentStartTime.toLocalDate() + " " + appointmentStartTime.toLocalTime().format(HH_mm) + "~" + appointmentEndTime.toLocalTime().format(HH_mm));
        }

        LocalDateTime serveStartTime = order.getServeStartTime();
        LocalDateTime serveEndTime = order.getServeEndTime();
        if (serveStartTime != null) {

            String s = serveStartTime.toLocalDate() + " " + serveStartTime.toLocalTime().format(HH_mm);
            if (serveEndTime != null) {
                s = s + "~" + serveEndTime.toLocalTime().format(HH_mm);
            }

            orderResponseDto.setServerTimeName(s);
        }

        if (StringUtils.isNotEmpty(orderResponseDto.getActivityDetail())) {
            orderResponseDto.setActivityDto(JSON.parseObject(orderResponseDto.getActivityDetail(), ActivityDto.class));

        }
        if (StringUtils.isNotEmpty(orderResponseDto.getCardCouponDetail())) {
            orderResponseDto.setMarketDto(JSON.parseObject(orderResponseDto.getCardCouponDetail(), MarketDto.class));
        }
        return orderResponseDto;
    }


    /**
     * 远程调用order中最新信息
     * 店铺信息
     * 发型师名称
     *
     * @param order
     */
    public void supplementOrder(Order order) {
        if (order == null) {
            return;
        }
        //补全卡券活动信息
        orderDomainService.queryOrderDetail(order);
        //补全店铺，发型师名称信息
        complementInfo(order);
        //log.info("supplementOrder order:{}", JSON.toJSONString(order));
        //查询发型师名称
        //order.setAdminName(adminRemoteService.getAdminName(order.getAdminId()));
        //查询发型师头像
        //order.setAdminAvatar(adminRemoteService.getAdminImg(order.getAdminId()));
    }

    /**
     * @return void
     * @description: 补全店铺，发型师名称信息
     * @author: ch
     * @Param [order]
     * @date: 2019-06-18 16:42
     **/
    public void complementInfo(Order order) {
        //查询店铺最新信息
        StoreRemoteDto storeRemoteDto = storeRemoteService.getByStoreId(order.getStoreId());
        if (storeRemoteDto != null) {
            BeanUtils.copyProperties(storeRemoteDto, order);
        }

        if (StringUtils.isNotBlank(order.getAdminId())) {
            CraftsmanDTO admin = adminRemoteService.getAdmin(order.getAdminId());
            //log.info("{} supplementOrder admin:{}",order.getAdminId(), JSON.toJSONString(admin));
            if (admin != null) {
                order.setAdminName(admin.getName());
                order.setAdminAvatar(admin.getPath());
                order.setAdminCode(admin.getCode() + "");
                order.setAdminNickName(admin.getNickName());
            }
        }

        if (StringUtils.isNotBlank(order.getAppointmentAdminId())) {

            CraftsmanDTO admin = adminRemoteService.getAdmin(order.getAppointmentAdminId());
            //log.info("{} supplementOrder admin:{}",order.getAppointmentAdminId(), JSON.toJSONString(admin));
            if (admin != null) {
                order.setAppointmentAdminName(admin.getName());
                order.setAppointmentAdminAvatar(admin.getPath());

                order.setAppointmentAdminCode(admin.getCode() + "");
                order.setAppointmentAdminNickName(admin.getNickName());
                order.setAppointmentAdminMobile(admin.getPhone());
            }

        }
    }


    /**
     * 根据用户id和cityid查询用户查上一单信息
     *
     * @param orderUserParamDto
     * @return
     */
    public String queryOrderInfo(OrderUserParamDto orderUserParamDto) {
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        // 获取账号合并ids
        String[] strings = adminRemoteService.queryUserIds(orderUserParamDto.getUserId());
        queryWrapper.in(Order::getUserId, strings);
//        queryWrapper.eq(Order::getUserId, orderUserParamDto.getUserId());
        if (StringUtils.isNotBlank(orderUserParamDto.getCityId())) {
            queryWrapper.eq(Order::getCityId, orderUserParamDto.getCityId());
        }
        queryWrapper.eq(Order::getServiceDown, 1);
        queryWrapper.orderByDesc(Order::getCreatedTime).last("LIMIT 1");
        Order order = orderMapper.selectOne(queryWrapper);
        if (order != null) {
            return String.valueOf(order.getStoreId());
        }
        return "";
    }


    /**
     * 根据用户查询用户的完成的服务订单(小程序使用)
     *
     * @param userId
     * @return
     */
    public List<Order> queryOrders(String userId) {
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        // 获取账号合并ids
        String[] strings = adminRemoteService.queryUserIds(userId);
        queryWrapper.in(Order::getUserId, strings);
//        queryWrapper.eq(Order::getUserId, userId);
        queryWrapper.eq(Order::getServiceDown, 1);
        queryWrapper.orderByDesc(Order::getCreatedTime);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        return orders;
    }


    /**
     * 查询用户未支付订单
     *
     * @param userId
     * @return
     */
    public Order queryOrdersNotPay(String userId) {
        // 获取账号合并ids
        String[] strings = adminRemoteService.queryUserIds(userId);
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().lambda().in(Order::getUserId, strings).eq(Order::getStatus, OrderStatus.NOT_PAY).orderByDesc(Order::getCreatedTime).last("LIMIT 1"));

        if (order != null) {
            supplementOrder(order);
        }

        return order;
    }


    public OrderServiceDto orderServices(String userId) {
        OrderServiceDto orderServiceDto = new OrderServiceDto();
        List<Order> orders = queryOrders(userId);
        if (!orders.isEmpty()) {
            Order order = orders.get(0);
            int daysNum = Period.between(order.getCreatedTime().toLocalDate(), LocalDateTime.now().toLocalDate()).getDays();
            orderServiceDto.covert(orders, daysNum);
        }
        return orderServiceDto;
    }


    /**
     * 获取未支付订单order（小程序）
     *
     * @param userId
     * @return
     */
    public String getNotPayOrderNo(String userId) {
        Order order = queryOrdersNotPay(userId);
        if (order != null) {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime createdTime = order.getCreatedTime().plusSeconds(60);
            if (now.isBefore(createdTime)) {
                return order.getOrderNo();
            }
        }
        return "";
    }

    /**
     * 获取未支付订单order（小程序）
     *
     * @param userId
     * @return
     */
    public Order getNotPayOrderInfo(String userId) {
        Order order = queryOrdersNotPay(userId);
        if (order != null) {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime createdTime = order.getCreatedTime().plusSeconds(60);
            if (now.isBefore(createdTime)) {
                return order;
            }
        }
        return null;
    }


    /**
     * 根据用户id 店铺id 判断该店铺id是否是该用户上次服务的店铺 （小程序）
     *
     * @return true 是上次服务的店铺
     * false 不是上次服务的店铺
     */
    public boolean lastService(String userId, String storeId) {
        OrderUserParamDto orderUserParamDto = new OrderUserParamDto();
        orderUserParamDto.setUserId(userId);
        String queryStoreId = queryOrderInfo(orderUserParamDto);
        if (queryStoreId.equals(storeId)) {
            return true;
        }
        return false;
    }


    /**
     * 根据订单号列表，查询店铺信息
     *
     * @param orderNos
     * @return
     */
    public List<OrderDetailResponseDto> queryOrders(String[] orderNos) {
        if (orderNos == null || orderNos.length == 0)
            throw new BusinessException(BusinessException.Type.DEFAULT, "订单No不存在");
        List<Order> order = orderMapper.selectList(new QueryWrapper<Order>().lambda().in(Order::getOrderNo, orderNos));
        orderDomainService.queryOrdersDetail(order);
        List<OrderDetailResponseDto> list = order.stream().map(this::queryByOrderNos)
                .collect(Collectors.toList());
        return list;

    }


    /**
     * 处理订单列表
     *
     * @param order
     * @return
     */
    public OrderDetailResponseDto queryByOrderNos(Order order) {
//        supplementOrder(order);
        //门店详情
        StoreRemoteDto storeRemoteDto = storeRemoteService.queryStore(order.getStoreId(), order.getServiceTypeId() + "");
        if (storeRemoteDto != null) {
            BeanUtils.copyProperties(storeRemoteDto, order);

        }

        OrderDetailResponseDto orderDetailResponseDto = new OrderDetailResponseDto();
        BeanUtils.copyProperties(order, orderDetailResponseDto);

        orderDetailResponseDto.setStatusName(order.getStatus().getValue());
        orderDetailResponseDto.setServiceTypeName(order.getServiceTypeName());
        orderDetailResponseDto.setPayTypeName(order.getPayType() != null ? order.getPayType().getValue() : "");
        orderDetailResponseDto.setOrderSourceName(order.getOrderSource().getName());
        try {
            String s = order.getAppointmentStartTime().toLocalDate() + " " + order.getAppointmentStartTime().toLocalTime().format(HH_mm) + "~" + order.getAppointmentEndTime().toLocalTime().format(HH_mm);
            orderDetailResponseDto.setAppointmentTimeShow(s);
        } catch (Exception e) {

        }


        try {
            String s1 = order.getServeStartTime().toLocalDate() + " " + order.getServeStartTime().toLocalTime().format(HH_mm) + "~" + order.getServeEndTime().toLocalTime().format(HH_mm);
            orderDetailResponseDto.setServiceTimeShow(s1);
        } catch (Exception e) {
        }

        try {
            orderDetailResponseDto.setServiceTimeLast(DateTimeUtils.minuteAndSecond(order.getServeStartTime(), order.getServeEndTime()));
        } catch (Exception e) {
        }
        String qrcodeUrl = orderDomainService.qrcodeUrl(orderDetailResponseDto.getTicketCode(), orderDetailResponseDto.getStoreId());
        orderDetailResponseDto.setTicketCodeUlr(qrcodeUrl);
        orderDetailResponseDto.covert();
        return orderDetailResponseDto;
    }


    /**
     * 查询用户完成订单 统计
     *
     * @param userId
     * @return
     */
    public Integer queryServiceDown(String userId, String storeId) {
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        // 获取账号合并ids
        String[] strings = adminRemoteService.queryUserIds(userId);
        queryWrapper.in(Order::getUserId, strings);
//        queryWrapper.eq(Order::getUserId, userId);
        queryWrapper.eq(Order::getServiceDown, 1);
        if (StringUtils.isNotBlank(storeId)) {
            queryWrapper.eq(Order::getStoreId, storeId);
        }
        Integer count = orderMapper.selectCount(queryWrapper);
        return count;

    }

    /**
     * 获取用户类型
     *
     * @param userId
     * @param storeId
     * @return 用户类型 0 全部用户，1 星客多新用户，2 门店新用户
     */
    public int queryUserType(String userId, String storeId) {

        //星客多新用户
        if (queryServiceDown(userId, null) == 0) {
            return 1;
        }

        //门店新用户
        if (queryServiceDown(userId, storeId) == 0) {
            return 2;
        }

        return 0;
    }

    public Object adminStoreList(String adminId) {


        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        queryWrapper.select(Order::getStoreId, Order::getStoreName);

        queryWrapper.eq(Order::getAdminId, adminId);

        queryWrapper.or(i -> i.eq(Order::getAppointmentAdminId, adminId));

        queryWrapper.groupBy(Order::getStoreId);

        List<Map<String, Object>> maps = orderMapper.selectMaps(queryWrapper);

        return maps;
    }

    public Object adminListAdmin(String storeId) {
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        queryWrapper.select(Order::getAdminId, Order::getAdminName);
        queryWrapper.eq(Order::getStoreId, storeId);
        queryWrapper.groupBy(Order::getAdminId);
        List<Map<String, Object>> maps = orderMapper.selectMaps(queryWrapper).stream().filter(Objects::nonNull).collect(Collectors.toList());
        return maps;
    }

    public Object adminListAppointment(String storeId) {
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        queryWrapper.select(Order::getAppointmentAdminId, Order::getAppointmentAdminName);
        queryWrapper.eq(Order::getStoreId, storeId);
        queryWrapper.groupBy(Order::getAppointmentAdminId);
        List<Map<String, Object>> maps = orderMapper.selectMaps(queryWrapper).stream().filter(Objects::nonNull).collect(Collectors.toList());
        return maps;
    }


    /**
     * 根据卡券ids 查询卡券信息
     *
     * @param marketingIds
     * @return
     */
    public List<OrderDetailResponseDto> marketing(String[] marketingIds, String marketingType) {
        if (marketingIds.length == 0)
            throw new BusinessException(BusinessException.Type.DEFAULT, "卡券id不存在");
        List<Order> order = orderMapper.selectList(new QueryWrapper<Order>().lambda().eq(Order::getMarketingType, marketingType).in(Order::getMarketingId, marketingIds));
        orderDomainService.queryOrdersDetail(order);
        List<OrderDetailResponseDto> list = order.stream().map(this::queryByOrderNos)
                .collect(Collectors.toList());
        return list;

    }

    public void refundSuccessMessage(Order order) {
        try {
            StatisticsServiceDto build = StatisticsServiceDto.builder()
                    .id(order.getUserId())
                    .refundMoney(order.getPayPrice())
                    .consumNotice(ConsumNoticeEnums.REFUND_SUCCESS)
                    .orderNo(order.getOrderNo())
                    .build();

            String insert = adminFeignService.insert(build);
            log.info("StatisticsServiceDto: {}, {}", JSON.toJSONString(build), insert);
        } catch (Exception e) {
            log.error("refundSuccessMessage error:{}", e);
        }
    }

    public void completeSuccessMessage(Order order) {
        try {
            StatisticsServiceDto build = StatisticsServiceDto.builder()
                    .id(order.getUserId())
                    .serviceMoney(order.getPayPrice())
                    .lastTime(order.getServeStartTime())
                    .consumNotice(ConsumNoticeEnums.CONSUME_SUCCESS)
                    .orderNo(order.getOrderNo())
                    .build();

            String marketingType = order.getMarketingType();
            if ("1".equals(marketingType)) {
                build.setCouponId(order.getMarketingId());
            }

            String insert = adminFeignService.insert(build);
            log.info("StatisticsServiceDto: {}, {}", JSON.toJSONString(build), insert);
        } catch (Exception e) {
            log.error("completeSuccessMessage error:{}", e);
        }
    }


    /**
     * 获取用户的首次服务时间，上最后一次服务时间
     *
     * @param userId
     * @param type
     * @return
     */
    public Order firstAndEnd(String userId, String type) {
        String[] strings = adminRemoteService.queryUserIds(userId);
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        queryWrapper.in(Order::getUserId, strings).eq(Order::getStatus, EVALUATION_DONE);
        if ("1".equals(type)) {
            queryWrapper.orderByDesc(Order::getServeStartTime);
        } else {
            queryWrapper.orderByAsc(Order::getServeStartTime);
        }
        queryWrapper.last("LIMIT 1");
        Order order = orderMapper.selectOne(queryWrapper);
        return order;

    }


    public Map<String, String> orderFirstAndEnd(String userId) {
        Map<String, String> map = new HashMap<>();
        map.put("firstTime", getOrderServiceTime(userId, "0"));
        map.put("endTime", getOrderServiceTime(userId, "1"));
        return map;

    }


    public String getOrderServiceTime(String userId, String type) {
        Order order = firstAndEnd(userId, type);
        if (order != null) {
            return DateTimeUtils.yyyy_MM_dd_HH_mm_ss(order.getServeStartTime()) + "~" + DateTimeUtils.HH_mm_ss(order.getServeEndTime());
        }
        return "";
    }


    public Order userPre(String userIds) {
        String[] strings = userIds.split(",");
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        queryWrapper
                .in(Order::getUserId, strings)
                .eq(Order::getServiceDown, true)
                .orderByDesc(Order::getServeStartTime)
                .last("LIMIT 1");
        Order order = orderMapper.selectOne(queryWrapper);
        return order;
    }


    /**
    * @description: 获取订单号
    * @author: ch
    * @Param [orders]
    * @return java.lang.String[]
    * @date: 2019-08-06 16:49
    **/
    public List<Object>  queryorserNos(List<Order> orders) {
        if (orders.isEmpty()) {
            return new ArrayList<>();
        }
        String[] orderNos = orders.stream().map(Order::getOrderNo).toArray(String[]::new);
        List<Object> objects = cutomerQueyService.cutomerList(orderNos);
        return objects;
    }
}

